<template>
  <div class="expert-assessment bg-background text-foreground p-4">
    <h2 class="mb-4 text-2xl font-bold">专家动态评估管理</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">
      <!-- <query-form :model="search" :formItems="formItems" @search="searchExperts" @reset="resetSearch" /> -->
      <el-form :inline="true" :model="search" class="query-form-inline">
        <el-form-item label="专家编码：">
          <el-input v-model="search.expert_code" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="专家姓名：">
          <el-input v-model="search.expert_name" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item label="专业领域：">
          <el-select class="search-select" v-model="search.major" placeholder="请选择" clearable>
            <el-option label="化学工程与技术" value="化学工程与技术" />
            <el-option label="安全科学与工程" value="安全科学与工程" />
            <el-option label="环境科学与工程" value="环境科学与工程" />
            <el-option label="化学工程与工艺" value="化学工程与工艺" />
            <el-option label="安全工程" value="安全工程" />
            <el-option label="环境工程" value="环境工程" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="评估时间：">
          <input type="month" v-model="search.assessment_date"
            class="input-time-query mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
        </el-form-item> -->
        <el-form-item label="评估年份：">
          <el-select class="search-select" v-model="search.assess_year" placeholder="请选择" clearable>
            <el-option v-for="year in years" :label="year" :key="year" :value="year"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评估周期：">
          <el-select class="search-select" v-model="search.judging_cycle" placeholder="请选择" clearable>
            <el-option label="年" value="年" />
            <el-option label="上半年" value="上半年" />
            <el-option label="下半年" value="下半年" />
          </el-select>
        </el-form-item>
        <el-form-item class="query-btns">
          <el-button @click="resetSearch" style="width: 75px; height: 30px;">重置</el-button>
          <el-button type="primary" @click="searchExperts" style="width: 75px; height: 30px;">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
      <el-button type="primary" @click="openAddDialog"
        style="width: 75px; height: 30px;float: right;margin-right: 48px;">评估</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedExpertData" style="width: 100%"
        @selection-change="handleSelectionChange" ref="table" align="center" class="data-table"
        :header-cell-style="headerCellStyle" empty-text="暂无数据">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column prop="expert_code" label="专家编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="assessment_date" label="评估时间" header-align="center" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.assessment_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="assess_year" label="评估年份" header-align="center" align="center"></el-table-column>
        <el-table-column prop="judging_cycle" label="评估周期" header-align="center" align="center"></el-table-column>
        <el-table-column prop="expert_name" label="专家姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="gender" label="性别" header-align="center" align="center"></el-table-column>
        <el-table-column prop="birth_date" label="出生年月" header-align="center" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.birth_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="major" label="专业" header-align="center" align="center"></el-table-column>
        <el-table-column prop="education" label="学历" header-align="center" align="center"></el-table-column>
        <el-table-column prop="title" label="职称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="department" label="所属单位" header-align="center" align="center"></el-table-column>
        <el-table-column prop="certificate" label="资格证书" header-align="center" align="center">
          <template #default="scope">
            {{ formatData(scope.row.certificate, 'book_array') }}
          </template>
        </el-table-column>
        <el-table-column prop="training_record" label="培训记录" header-align="center" align="center">
          <template #default="scope">
            {{ formatData(scope.row.training_record, 'training_array') }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="参与应急处置数量" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ability" label="应急处置能力" header-align="center" align="center"></el-table-column>
        <el-table-column prop="overall_rating" label="总体评价" header-align="center" align="center"></el-table-column>
      </el-table>
    </div>

    <!-- Pagination -->
    <div
      class="flex items-center justify-between px-4 py-3 bg-card text-card-foreground border-t border-border sm:px-6">
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>

    <!-- Add Expert Dialog -->
    <el-dialog class="dialog-from" v-model="isAddDialogOpen" :title="isDialogType == 'add' ? '应急专家动态评估' : '应急专家动态评估'"
      width="900" destroy-on-close align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-form :model="expertForm" label-width="auto" :rules="rules" ref="formRef">
            <el-row :gutter="120" class="row-item">
              <el-col :span="8">
                <el-form-item label="选择年份：" label-position="top" prop="assess_year">
                  <el-select v-model="expertForm.assess_year" :disabled="disabledType">
                    <el-option v-for="year in years" :label="year" :key="year" :value="year"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8"></el-col>
              <el-col :span="8"></el-col>
            </el-row>
            <el-row :gutter="120" class="row-item">
              <el-col :span="8">
                <el-form-item label="评选周期：" label-position="top" prop="judging_cycle">
                  <el-select v-model="expertForm.judging_cycle" placeholder="请选择" :disabled="disabledType" clearable
                    @change="handleYearChange">
                    <el-option label="年" value="年" />
                    <el-option label="上半年" value="上半年" />
                    <el-option label="下半年" value="下半年" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="专家姓名：" label-position="top" prop="expert_name">
                  <el-select v-model="expertForm.expert_name" filterable placeholder="请选择" clearable
                    @change="handleChange" :disabled="!expertForm.assess_year || !expertForm.judging_cycle">
                    <el-option v-for="year in searchExpertsData" :label="year.expert_name" :key="year.id"
                      :value="year"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="专家编码：" label-position="top" prop="expert_code">
                  <el-input v-model="expertForm.expert_code" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <template v-if="expertForm.expert_code">
              <el-row :gutter="120" class="row-item">
                <el-col :span="8">
                  <el-form-item label="性别：" label-position="top" prop="gender">
                    <el-select v-model="expertForm.gender" placeholder="请选择" clearable disabled>
                      <el-option label="男" value="男" />
                      <el-option label="女" value="女" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出生年月：" label-position="top" prop="birth_date">
                    <input type="date" disabled v-model="expertForm.birth_date"
                      class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="专业：" label-position="top" prop="major">
                    <el-select v-model="expertForm.major" placeholder="请选择" clearable disabled>
                      <el-option label="化学工程与技术" value="化学工程与技术" />
                      <el-option label="安全科学与工程" value="安全科学与工程" />
                      <el-option label="环境科学与工程" value="环境科学与工程" />
                      <el-option label="化学工程与工艺" value="化学工程与工艺" />
                      <el-option label="安全工程" value="安全工程" />
                      <el-option label="环境工程" value="环境工程" />
                      <el-option label="其他" value="其他" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="120" class="row-item">
                <el-col :span="8">
                  <el-form-item label="学历：" label-position="top" prop="education">
                    <el-select v-model="expertForm.education" placeholder="请选择" clearable disabled>
                      <el-option label="大专" value="大专" />
                      <el-option label="本科" value="本科" />
                      <el-option label="硕士" value="硕士" />
                      <el-option label="博士" value="博士" />
                      <el-option label="其他" value="其他" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="职称：" label-position="top" prop="title">
                    <el-select v-model="expertForm.title" placeholder="请选择" clearable disabled>
                      <el-option label="高级工程师" value="高级工程师" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所属单位：" label-position="top" prop="department">
                    <el-select v-model="expertForm.department" placeholder="请选择" clearable disabled>
                      <el-option label="陕西侨岭润岳生物科技有限公司" value="陕西侨岭润岳生物科技有限公司" />
                      <el-option label="陕西格丽达生物科技有限公司" value="陕西格丽达生物科技有限公司" />
                      <el-option label="陕西妙龙居新材料科技有限公司" value="陕西妙龙居新材料科技有限公司" />
                      <el-option label="大荔瑞联新材料股份有限责任公司" value="大荔瑞联新材料股份有限责任公司" />
                      <el-option label="大荔海泰新材料有限责任公司" value="大荔海泰新材料有限责任公司" />
                      <el-option label="陕西科谱华生物科技有限公司" value="陕西科谱华生物科技有限公司" />
                      <el-option label="陕西北农华绿色生物技术有限公司" value="陕西北农华绿色生物技术有限公司" />
                      <el-option label="陕西萌益生物科技有限公司" value="陕西萌益生物科技有限公司" />
                      <el-option label="西安益维聚泰新材料科技有限公司" value="西安益维聚泰新材料科技有限公司" />
                      <el-option label="西安德立生物化工有限公司" value="西安德立生物化工有限公司" />
                      <el-option label="陕西同州蔚隆化学科技有限公司" value="陕西同州蔚隆化学科技有限公司" />
                      <el-option label="陕西港华生物科技有限公司" value="陕西港华生物科技有限公司" />
                      <el-option label="陕西迈祥有机玻璃科技有限公司" value="陕西迈祥有机玻璃科技有限公司" />
                      <el-option label="陕西英唐食用新材料科技有限公司" value="陕西英唐食用新材料科技有限公司" />
                      <el-option label="光大绿色环保城乡再生能源（大荔）有限公司" value="光大绿色环保城乡再生能源（大荔）有限公司" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="120" class="row-item">
                <el-col :span="8">
                  <el-form-item label="联系方式：" label-position="top" prop="contact_number">
                    <el-input type="number" v-model="expertForm.contact_number" placeholder="请输入" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8"></el-col>
                <el-col :span="8"></el-col>
              </el-row>
              <!-- <el-row :gutter="80" class="row-item"> -->
              <!-- <el-col :span="8"> -->
              <el-form-item style="margin-bottom: 0;" label="资格证书：" label-position="top" prop="certificate">
                <div class="assessment-input-box">
                  <div class="assessment-input-item" v-for="(item, index) in assessmentList" :key="index">
                    <el-input class="assessment-input" v-model="item.book_array" placeholder="请输入" />
                    <el-button class="assessment-input-btn" @click="closeAssessmentList(index)">X</el-button>
                  </div>
                  <el-button type="primary" text class="assessment-input assessment-btn"
                    @click="addAssessment">+添加证书</el-button>
                </div>
              </el-form-item>
              <el-form-item style="margin-bottom: 0;" label="培训记录：" label-position="top" prop="training_record">
                <div class="assessment-input-box">
                  <div class="assessment-input-item" v-for="(item, index) in trainingList" :key="index">
                    <el-input class="assessment-input" v-model="item.training_array" placeholder="请输入" />
                    <el-button class="assessment-input-btn" @click="closeTrainingList(index)">X</el-button>
                  </div>
                  <el-button type="primary" text class="assessment-input assessment-btn"
                    @click="addTraining">+添加记录</el-button>
                </div>
              </el-form-item>
              <el-form-item style="margin-bottom: 0;" label="参与应急处置事故：" label-position="top" prop="accident">
                <div class="assessment-input-box">
                  <div class="assessment-input-item" v-for="(item, index) in accidentList" :key="index">
                    <el-input class="assessment-input" v-model="item.accident_array" placeholder="请输入" />
                    <el-button class="assessment-input-btn" @click="closeAccidentList(index)">X</el-button>
                  </div>
                  <el-button type="primary" text class="assessment-input assessment-btn"
                    @click="addAccident">+添加</el-button>
                </div>
              </el-form-item>
              <!-- </el-col> -->
              <!-- </el-row> -->
            </template>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addExpert">确认</el-button>
          <el-button @click="isAddDialogOpen = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <el-row :gutter="80" class="row-item">
                <el-col :span="8"><el-form-item label="培训记录：" label-position="top" prop="training_record">
                    <el-select v-model="expertForm.training_record" placeholder="请输入" clearable>
                      <el-input v-model="expertForm.expert_code" />
                    </el-select>
                  </el-form-item></el-col>
                <el-col :span="8"><el-form-item label="可用状态：" label-position="top" prop="availability_status">
                    <el-select v-model="expertForm.availability_status" placeholder="请选择" clearable>
                      <el-option label="在职" value="在职" />
                      <el-option label="离职" value="离职" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row> -->

    <!-- View Expert Dialog -->
    <el-dialog class="dialog-from" v-model="isViewDialogOpen" title="应急专家动态评估详情" width="900" destroy-on-close
      align-center>
      <div class="body-item">
        <div class="box-title">
          <div class="box-color"></div><strong>基本信息</strong>
        </div>
        <div class="box-content">
          <el-descriptions title="" :column="3">
            <el-descriptions-item label="专家编码：">{{ viewingExpert.expert_code }}</el-descriptions-item>
            <el-descriptions-item label="专家姓名：">{{ viewingExpert.expert_name }}</el-descriptions-item>
            <el-descriptions-item label="性别：">{{ viewingExpert.gender }}</el-descriptions-item>
            <el-descriptions-item label="出生年月：">{{ viewingExpert.expert_time }}</el-descriptions-item>
            <el-descriptions-item label="年龄：">{{ viewingExpert.age }}</el-descriptions-item>
            <el-descriptions-item label="专业：">{{ viewingExpert.field }}</el-descriptions-item>
            <el-descriptions-item label="学历：">{{ viewingExpert.education }}</el-descriptions-item>
            <el-descriptions-item label="职称：">{{ viewingExpert.title }}</el-descriptions-item>
            <el-descriptions-item label="所属单位：">{{ viewingExpert.organization }}</el-descriptions-item>
            <el-descriptions-item label="资格证书：">{{ viewingExpert.certificate }}</el-descriptions-item>
            <el-descriptions-item label="培训记录：">{{ viewingExpert.training_record }}</el-descriptions-item>
            <el-descriptions-item label="可用状态：">{{ viewingExpert.availability_status }}</el-descriptions-item>
            <el-descriptions-item label="联系方式：" :span="3">55456421564684</el-descriptions-item>
            <el-descriptions-item label="备注：" :span="3">打唔打稳定上分我打个搭嘎</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addExpert">确认</el-button>
          <el-button @click="closeViewDialog">
            取消
          </el-button>
        </div>
      </template> -->
    </el-dialog>


    <!-- Edit Expert Dialog -->
    <div v-if="isEditDialogOpen"
      class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
      <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
        <div class="mb-4 flex items-center justify-between">
          <h3 class="text-lg font-bold">编辑应急专家</h3>
          <button @click="closeEditDialog" class="text-muted-foreground hover:text-foreground">
            <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <form @submit.prevent="updateExpert">
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label for="edit_expert_code" class="block text-sm font-medium text-gray-700">专家编码：</label>
              <input type="text" id="edit_expert_code" v-model="editingExpert.expert_code"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_expert_name" class="block text-sm font-medium text-gray-700">专家姓名：</label>
              <input type="text" id="edit_expert_name" v-model="editingExpert.expert_name"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_gender" class="block text-sm font-medium text-gray-700">性��：</label>
              <select id="edit_gender" v-model="editingExpert.gender"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="男">男</option>
                <option value="女">女</option>
              </select>
            </div>
            <div>
              <label for="edit_age" class="block text-sm font-medium text-gray-700">年龄：</label>
              <input type="number" id="edit_age" v-model="editingExpert.age"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_field" class="block text-sm font-medium text-gray-700">专业：</label>
              <input type="text" id="edit_field" v-model="editingExpert.field"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_education" class="block text-sm font-medium text-gray-700">学历：</label>
              <input type="text" id="edit_education" v-model="editingExpert.education"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_title" class="block text-sm font-medium text-gray-700">职称：</label>
              <input type="text" id="edit_title" v-model="editingExpert.title"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_organization" class="block text-sm font-medium text-gray-700">所属单位：</label>
              <input type="text" id="edit_organization" v-model="editingExpert.organization"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_certificate" class="block text-sm font-medium text-gray-700">资格证书：</label>
              <input type="text" id="edit_certificate" v-model="editingExpert.certificate"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_training_record" class="block text-sm font-medium text-gray-700">培训记录：</label>
              <input type="text" id="edit_training_record" v-model="editingExpert.training_record"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
            <div>
              <label for="edit_availability_status" class="block text-sm font-medium text-gray-700">可用状态：</label>
              <select id="edit_availability_status" v-model="editingExpert.availability_status"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                <option value="在职">在职</option>
                <option value="离职">离职</option>
              </select>
            </div>
            <div>
              <label for="edit_overall_rating" class="block text-sm font-medium text-gray-700">综合评价：</label>
              <input type="text" id="edit_overall_rating" v-model="editingExpert.overall_rating"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
            </div>
          </div>
          <div class="mt-4">
            <label for="edit_contact_method" class="block text-sm font-medium text-gray-700">联系方式：</label>
            <input type="text" id="edit_contact_method" v-model="editingExpert.contact_method"
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
          </div>
          <div class="mt-4">
            <label for="edit_remarks" class="block text-sm font-medium text-gray-700">备注：</label>
            <textarea id="edit_remarks" v-model="editingExpert.remarks" rows="3"
              class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"></textarea>
          </div>
          <div class="mt-4 flex justify-end">
            <button type="submit" class="bg-primary text-primary-foreground mr-2 rounded px-4 py-2">
              确定
            </button>
            <button type="button" @click="closeEditDialog"
              class="bg-secondary text-secondary-foreground rounded px-4 py-2">
              取消
            </button>
          </div>
        </form>
      </div>
    </div>


    <!-- <div v-if="isViewDialogOpen"
      class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
      <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
        View dialog content
      </div>
    </div> -->

    <!-- Import Dialog -->
    <div v-if="isImportDialogOpen"
      class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
      <div class="bg-card text-card-foreground w-[400px] rounded-lg p-5 shadow-xl">
        <h3 class="mb-4 text-lg font-bold">导入专家记录</h3>
        <input accept=".csv, .xlsx"
          class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/80 mb-4 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold"
          type="file" @change="handleFileUpload" />
        <div class="flex justify-end">
          <button class="bg-primary text-primary-foreground mr-2 rounded px-4 py-2" @click="importData">
            导入
          </button>
          <button class="bg-secondary text-secondary-foreground rounded px-4 py-2" @click="closeImportDialog">
            取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
import { ElMessage, ElMessageBox } from 'element-plus'
// import {
//   Minus
// } from 'element-plus/icons-vue'
// import QueryForm from '../../../components/QueryForm.vue'; // 使用相对路径
const { proxy } = getCurrentInstance()
const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/expert-assessment'
})
const currentYear = new Date().getFullYear();
const years = ref([]);
// 生成年份数组，例如从1950到当前年份
for (let i = 1950; i <= currentYear; i++) {
  years.value.unshift(i);
}
// 搜索相关
const search = ref({
  expert_code: '',
  expert_name: '',
  major: '',
  // assessment_date: '',
  assess_year: '',
  judging_cycle: '',
})

const formItems = ref([
  {
    label: '专家编码：',
    model: 'expert_code',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '专家姓名：',
    model: 'expert_name',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '专业领域：',
    model: 'field',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '化学工程', value: '化学工程' },
      { label: '火灾防护', value: '火灾防护' },
    ],
  },
  {
    label: '职称：',
    model: 'title',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '高级工程师', value: '高级工程师' },
    ],
  },
]);
const handleYearChange = (data) => {
  // console.log(expertForm.value)
};
const matchResult = ref(null);
const disabledType = ref(false)
const handleChange = (data) => {
  if (data) {
    disabledType.value = true
    expertForm.value = { ...expertForm.value, ...data, birth_date: formatDateEdit(data.birth_date) }
    matchResult.value = experts.value.some(expertItem =>
      expertItem.expert_name == expertForm.value.expert_name &&
      expertItem.assess_year == expertForm.value.assess_year &&
      expertItem.judging_cycle == expertForm.value.judging_cycle &&
      expertItem.expert_code == expertForm.value.expert_code
    );
    if (matchResult.value) {
      alert('该专家记录已存在，请勿重复添加！')
      resetExpertForm()
      disabledType.value = false
    }
  } else {
    disabledType.value = false
    resetExpertForm()
    matchResult.value = false
  }
  assessmentList.value = [{ book_array: '' }]
  trainingList.value = [{ training_array: '' }]
  accidentList.value = [{ accident_array: '' }]




  console.log('experts', experts.value)
  console.log('expertForm', expertForm.value)
  console.log('matchResult', matchResult.value)
};
const formatDateEdit = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以要加1
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 数据相关
const loading = ref(false)
const experts = ref([])
const allChecked = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const jumpToPage = ref(1)
const selectedIds = ref([])

// 对话框状态
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const importFile = ref(null)
// 专家表单
const expertForm = ref({
  id: null,
  assess_year: currentYear,
  certificate: '',
  judging_cycle: '',
  training_record: '',
  admin_div: '',
  park_code: '',
  expert_code: '',
  expert_name: '',
  gender: '',
  birth_date: '',
  education: '',
  major: '',
  title: '',
  department: '',
  contact_number: '',
  email: '',
})
const rules = {
  assess_year: [
    { required: true, message: '请选择年份', trigger: 'change' },
  ],
  judging_cycle: [
    { required: true, message: '请选择评选周期', trigger: 'change' },
  ],
  expert_name: [
    { required: true, message: '请输入专家姓名', trigger: 'change' },
  ],
  // certificate: [
  //   { validator: validateBookArray, trigger: 'blur' },
  // ],
  // certificate: [
  //   { required: true, message: '请输入资格证书', trigger: 'blur' },
  // ],
};
// function validateBookArray(rule, value, callback) {
//   if (!Array.isArray(value) || value.length === 0) {
//     return callback(new Error('资格证书不能为空'));
//   }
//   for (let i = 0; i < value.length; i++) {
//     if (!value[i].book_array) {
//       return callback(new Error(`第 ${i + 1} 本书名不能为空`));
//     }
//   }
//   callback(); // 验证通过
// }
// 新增状态变量
const isEditDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const editingExpert = ref({})
const viewingExpert = ref({})

// 计算属性
const totalItems = computed(() => experts.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

const displayedPages = computed(() => {
  const range = 2
  const start = Math.max(1, currentPage.value - range)
  const end = Math.min(totalPages.value, currentPage.value + range)
  return Array.from({ length: end - start + 1 }, (_, i) => start + i)
})

const displayedExpertData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return experts.value.slice(start, end)
})

// API 调用函数

const searchAllExperts = async () => {
  try {
    const response = await axios.get(`${proxy.$currentUrl}/api/resource-management/experts/search`)
    searchExpertsData.value = response.data
    // console.log(response)
  } catch (error) {
    console.error('搜索所有专家记录失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    alert(
      '搜索所有专家记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const searchExperts = async () => {
  try {
    loading.value = true;
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: search.value,
    })
    await searchAllExperts()
    experts.value = response.data
    currentPage.value = 1
    selectedIds.value = []
    allChecked.value = false
    loading.value = false;
  } catch (error) {
    console.error('搜索专家记录失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    alert(
      '搜索专家记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
// 添加 formatDate 函数
const formatDate = (dateString) => {
  const date = new Date(dateString);

  // 获取年份和月份
  const year = date.getUTCFullYear();
  const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1

  // 返回格式化后的日期字符串
  return `${year}/${month}`;
}
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)

  // 获取年份、月份和日期
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以要加1
  const day = String(date.getDate()).padStart(2, '0')

  // 返回格式化后的日期
  return `${year}/${month}/${day}`
}
const formatData = (dataString, arrayField) => {
  if (dataString) {
    const dataArray = JSON.parse(dataString);
    return dataArray.map(item => item[arrayField]).join(', ');
  }
}
// 解析字符串为对象

const resetSearch = () => {
  search.value = {
    expert_code: '',
    expert_name: '',
    major: '',
    assessment_date: '',
  }
  searchExperts()
}
const handleSelectionChange = (selected) => {
  selectedIds.value = selected;
};
const formRef = ref(null)
const filassessmentList = ref([]);
const filtrainingList = ref([]);
const filaccidentList = ref([]);
// 过滤函数
const filterList = (list, key) => {
  return list.filter(item => item[key] !== '');
};
// 提示函数
const showAlert = (message) => {
  alert(message);
};
const addExpert = async () => {
  try {
    await formRef.value.validate();
    // 过滤数据
    filassessmentList.value = filterList(assessmentList.value, 'book_array');
    filtrainingList.value = filterList(trainingList.value, 'training_array');
    filaccidentList.value = filterList(accidentList.value, 'accident_array');
    let alertMessage = '';

    // 检查并设置证书
    if (filassessmentList.value.length > 0) {
      expertForm.value.certificate = JSON.stringify(filassessmentList.value);
    } else {
      alertMessage += '请添加资格证书！\n';
    }

    // 检查并设置培训记录
    if (filtrainingList.value.length > 0) {
      expertForm.value.training_record = JSON.stringify(filtrainingList.value);
    } else {
      alertMessage += '请添加培训记录！\n';
    }
    // 检查并设置应急处置事故
    if (filaccidentList.value.length > 0) {
      expertForm.value.accident = JSON.stringify(filaccidentList.value);
    } else {
      alertMessage += '请添加应急处置事故！\n';
    }
    // 如果有提示信息，则显示一次
    if (alertMessage) {
      showAlert(alertMessage.trim());
    }
    // const response = await axios.post(`${apiBaseUrl.value}/add`, expertForm.value)
    // showAlert(response.data.message || '创建专家成功')
    ElMessageBox.confirm(
      '您确定要评估该专家吗?',
      '消息提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        ElMessage({
          type: 'success',
          message: '已确认',
        })
        axios.post(`${apiBaseUrl.value}/add`, expertForm.value)
        isAddDialogOpen.value = false
        searchExperts()
        resetExpertForm()
        // showAlert(response.data.message || '创建专家成功')
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
  } catch (error) {
    console.error('创建专家记录失败:', error);
    showAlert('创建专家记录失败: ' + (error.response?.data?.message || error.message));
  }
}
// const response = await axios.post(apiBaseUrl.value, expertForm.value)
// alert(response.data.message || '创建专家成功')
// // 不关闭对话框，而是清空表单
// resetExpertForm()
// isAddDialogOpen.value = false
// await searchExperts()
const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(
        selectedIds.value.map((id) =>
          axios.delete(`${apiBaseUrl.value}/${id}`),
        ),
      )
      alert('删除成功')
      selectedIds.value = []
      allChecked.value = false
      await searchExperts()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert(
        '删除记录失败: ' + (error.response?.data?.message || error.message),
      )
    }
  }
}

const exportData = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new()

  // 准备要导出的数据
  const exportData = experts.value.map((expert) => ({
    专家编码: expert.expert_code,
    评估时间: formatDate(expert.assessment_date),
    专家姓名: expert.expert_name,
    性别: expert.gender,
    出生年月: formatDateTime(expert.birth_date),
    专业: expert.major,
    学历: expert.education,
    职称: expert.title,
    所属单位: expert.department,
    资格证书: formatData(expert.certificate, 'book_array'),
    培训记录: formatData(expert.training_record, 'training_array'),
    参与应急处置数量: expert.quantity,
    应急处置能力: expert.ability,
    总体评价: expert.overall_rating,
  }))

  // 将数据转换为工作表
  const ws = XLSX.utils.json_to_sheet(exportData)

  // 将工作表添加到工作簿，并设置表名为"应急专家管理"
  XLSX.utils.book_append_sheet(wb, ws, '专家管理评估')

  // 生成二进制字符串
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为 Blob
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '专家管理评估.xlsx'

  // 模拟点击下载
  link.click()

  // 释放 URL 对象
  URL.revokeObjectURL(link.href)
}

// 添加 s2ab 辅助函数
function s2ab(s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}

// 导入相关数
const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
  console.log('File selected:', importFile.value.name)
}

const importData = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await searchExperts()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}
const isDialogType = ref('add')
// 对话框控制函数
const openAddDialog = () => {
  isDialogType.value = 'add';
  resetExpertForm()
  expertForm.value.year = new Date().getFullYear()
  isAddDialogOpen.value = true
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
  console.log('Add dialog closed')
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
  console.log('Import dialog opened')
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
  console.log('Import dialog closed')
}

// 分页相关函数
const changePageSize = () => {
  currentPage.value = 1
  // searchExperts()
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    // searchExperts()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    // searchExperts()
  }
}

const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    // searchExperts()
  }
}

const toggleSelectAll = () => {
  if (allChecked.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = displayedExpertData.value.map((expert) => expert.id)
  }
  allChecked.value = !allChecked.value
}

// 添加取消函数
const cancelAdd = () => {
  if (confirm('确定要取消添加吗？已输入的数据将会丢失。')) {
    resetExpertForm()
    isAddDialogOpen.value = false
  }
}

// 添加重置表单函数
const resetExpertForm = () => {
  disabledType.value = false
  expertForm.value = {
    id: null,
    assess_year: currentYear,
    certificate: '',
    judging_cycle: '',
    training_record: '',
    admin_div: '',
    park_code: '',
    expert_code: '',
    expert_name: '',
    gender: '',
    birth_date: '',
    education: '',
    major: '',
    title: '',
    department: '',
    contact_number: '',
    email: '',
  }
}

// 编辑专家
const editExpert = (expert) => {
  expertForm.value = { ...expert }
  resetExpertForm()
  isDialogType.value = 'edit';
  isAddDialogOpen.value = true;
  // editingExpert.value = { ...expert }
  // isEditDialogOpen.value = true
  // console.log('Editing expert:', editingExpert.value)
  // console.log('Edit dialog opened')

}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
  editingExpert.value = {}
  console.log('Edit dialog closed')
}

const updateExpert = async () => {
  try {
    const response = await axios.put(
      `${apiBaseUrl.value}/${editingExpert.value.id}`,
      editingExpert.value,
    )
    alert(response.data.message || '更新专家信息成功')
    closeEditDialog()
    await searchExperts()
  } catch (error) {
    console.error('更新专家信息失败:', error)
    alert(
      '更新专家信息失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const toggleItemSelection = (expert) => {
  const index = selectedIds.value.indexOf(expert.id)
  if (index === -1) {
    selectedIds.value.push(expert.id)
  } else {
    selectedIds.value.splice(index, 1)
  }
  allChecked.value =
    selectedIds.value.length === displayedExpertData.value.length
}

// 查看专家详情
const viewDetails = (expert) => {
  viewingExpert.value = { ...expert }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingExpert.value = {}
}

// 获取中文字段名
const getChineseFieldName = (key) => {
  const fieldNameMap = {
    expert_code: '专家编码',
    expert_name: '专家姓名',
    gender: '性别',
    age: '年龄',
    field: '专业',
    education: '学历',
    title: '职称',
    organization: '所属单位',
    certificate: '资格证书',
    training_record: '培训记录',
    availability_status: '可用状态',
    overall_rating: '综合评价',
    // ... 其他字段映射
  }
  return fieldNameMap[key] || key
}

// 格式化字段值
const formatFieldValue = (key, value) => {
  if (key === 'birthdate' && value) {
    return new Date(value).toLocaleDateString('zh-CN')
  }
  if (key === 'availability_status') {
    return value === 'active' ? '在职' : '离职'
  }
  if (key === 'gender') {
    return value === 'male' ? '男' : '女'
  }
  return value
}
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
let assessmentList = ref([{ book_array: '' }])
let trainingList = ref([{ training_array: '' }])
let accidentList = ref([{ accident_array: '' }])
const addAssessment = () => {
  assessmentList.value.push({ book_array: '' })
}
const closeAssessmentList = (index) => {
  if (assessmentList.value.length > 1) {
    assessmentList.value.splice(index, 1);
  }
}
const addTraining = () => {
  trainingList.value.push({ training_array: '' })
}
const closeTrainingList = (index) => {
  if (trainingList.value.length > 1) {
    trainingList.value.splice(index, 1);
  }
}
const addAccident = () => {
  accidentList.value.push({ accident_array: '' })
}
const closeAccidentList = (index) => {
  if (accidentList.value.length > 1) {
    accidentList.value.splice(index, 1);
  }
}
const searchExpertsData = ref([])
// 生命周期钩子
onMounted(() => {
  searchExperts()
  // searchAllExperts()
})
</script>

<style scoped>
/* 移除所有现有的样式 */
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.year-select {
  width: 100%;
  height: 34px;
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.year-select:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.assessment-input-box {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.assessment-input-item {
  display: inline-block;
  height: 32px;
  width: 33%;
  margin-right: 2px;
  margin-bottom: 20px;
  /* margin-right: 50px; */
  /* padding-right: 52px;
  margin-right: 26px; */
}

.assessment-input {
  width: 188px;
  display: inline-block;
}

.assessment-input-item:last-child {
  margin-right: 0;
  /* 最后一个子标签不需要右边距 */
}

.assessment-input-box>.assessment-input-item:nth-child(3n) {
  margin-right: 0;
  /* 最后一个子标签不需要右边距 */
}

:deep(.assessment-input .el-input__wrapper) {
  width: 188px;
}

.assessment-input-btn {
  display: inline-block;
  padding: 0;
  width: 18px;
  height: 18px;
  line-height: 15px;
  /* height: 100%; */
  text-align: center;
  margin-left: 10px;
  border-radius: 50%;
  color: #409eff;
}

.assessment-btn {
  width: 24%;
  border: 1px dashed #409eff;
}

.input-time-query {
  margin-top: 0;
  border-radius: 5%;
  display: inline-block;
  box-shadow: 0 0 0 1px #dcdfe6;
  width: 180px;
  height: 32px;
}

.input-time-query:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.search-select {
  width: 181px;
}

.query-form-inline :deep(.el-form-item) {
  margin-bottom: 0;
}

.query-form-inline :deep(.el-form-item .el-select) {
  width: 180px;
}

.query-btns {
  float: right;
}

/* .query-btns {
  margin: 0;
  text-align: right;
  width: 100%;
}

:deep(.query-btns .el-form-item__content) {
  display: inline-block;
} */
</style>
